package com.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.demo.bean.DongHuan;
import com.demo.service.JsonManageService;
import com.demo.service.RackReadService;
import com.demo.service.impl.JsonManageServiceImpl;
import com.demo.service.impl.RackReadServiceImpl;
import com.demo.util.ActiveMQPusher;
import com.demo.util.FormatUtil;
import com.demo.util.HttpSendPerf;
import com.demo.util.JSONReadUtil;
import com.demo.util.ReadExcel;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class PerfUploadController {
	/**
	 * 所要推送动环类型集合
	 */
	static List<String> dhlist;
	/**
	 * 所要推送动环设备list-map
	 */
	static Map<String, List<String>> donghuanMap;
	/**
	 * 推送房间集合
	 */
	static List<String> fjlist;
	/**
	 * 推送ip
	 */
	static String IP = "127.0.0.1";
	/**
	 * 推送服务url
	 */
	static String URL;

	JsonManageService jsonManageService;

	/**
	 * itvop-上传布局文件,获取动环设备编号
	 * 
	 * @param file       布局.json路径
	 * @param fangjian   推送房间参数
	 * @param ip         推送ip参数
	 * @param peidiangui 判断是否选中
	 * @param wenshidu   判断是否选中
	 * @param kongtiao   判断是否选中
	 * @param UPS        判断是否选中
	 * @param fadianji   判断是否选中
	 * @param all        判断是否选中
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "/uploadJsonPref", method = RequestMethod.POST)
	public String uploadJson(HttpServletRequest request, @RequestParam("file") MultipartFile file, String fangjian,
			String ip, String peidiangui, String wenshidu, String kongtiao, String UPS, String fadianji, String all)
			throws IllegalStateException, IOException {
		RackReadService rackReadService = new RackReadServiceImpl();
		dhlist = new ArrayList<String>();
		if (null != ip && !"".equals(ip)) {
			IP = ip;
		}
		if (null != wenshidu) {
			dhlist.add(wenshidu);
		}
		if (null != peidiangui) {
			dhlist.add(peidiangui);
		}
		if (null != kongtiao) {
			dhlist.add(kongtiao);
		}
		if (null != UPS) {
			dhlist.add(UPS);
		}
		if (null != fadianji) {
			dhlist.add(fadianji);
		}
		if (null != all) {
			System.out.println("------------------------------------------------------------------------");
			dhlist.add("温湿度");
			dhlist.add("配电柜");
			dhlist.add("空调");
			dhlist.add("UPS");
			dhlist.add("发电机");
		}
		System.out.println("房间编号为:");
		if (fangjian != null) {
			fjlist = new ArrayList<String>();
			String[] sourceStrArray = fangjian.split(",");
			for (int i = 0; i < sourceStrArray.length; i++) {
				if (!"".equals(sourceStrArray[i])) {
					fjlist.add(sourceStrArray[i]);
					System.out.print(sourceStrArray[i]);
				}
			}
		}
		if (!file.isEmpty()) {
			// 上传文件路径
			String path = request.getServletContext().getRealPath("/upload");
			// 上传文件名
			String filename = file.getOriginalFilename();
			File filepath = new File(path, filename);
			// 判断路径是否存在，如果不存在就创建一个
			if (!filepath.getParentFile().exists()) {
				filepath.getParentFile().mkdirs();
			}
			// 将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			String filePath = path + File.separator + filename;
			System.out.println("文件上传成功");
			System.out.println("文件路径：" + path + File.separator + filename);
			if (fjlist.size() != 0) {
				donghuanMap = rackReadService.readDongHuan(filePath, dhlist, fjlist);
			} else {
				donghuanMap = rackReadService.readDongHuan(filePath, dhlist);
			}
			System.out.println("动环编号:" + JSONObject.fromObject(donghuanMap));
			return ("/uploadPerf.action");
		}
		return ("pref_one.html");
	}

	/**
	 * itvop推送性能数据
	 * 
	 * @author LiaoMinJun
	 */
	@RequestMapping("/uploadPerf")
	public String uploadPerf() {
		JsonManageService service = new JsonManageServiceImpl();

		String classPath = this.getClass().getResource("/").getPath();
		System.out.println("读取数据：" + classPath + "/perfsetup.json");

		JSON dhjson = service.donghuanManage(donghuanMap, classPath + "/perfsetup.json");
		ActiveMQPusher perfacmq = new ActiveMQPusher("admin", "admin", "tcp://" + IP + ":61616", "perfQueue");
		System.out.println("动环数据:" + dhjson.toString());
		perfacmq.push2ActiveMQ(dhjson.toString());
		System.gc();
		return "pref_succeed.html";
	}

	/**
	 * Tarsier-上传布局文件,获取动环设备编号
	 * 
	 * @param file       布局.json路径
	 * @param fangjian   推送房间参数
	 * @param url        推送NOAH参数
	 * @param peidiangui 判断是否选中
	 * @param wenshidu   判断是否选中
	 * @param kongtiao   判断是否选中
	 * @param UPS        判断是否选中
	 * @param fadianji   判断是否选中
	 * @param all        判断是否选中
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "/uploadJsonPrefs", method = RequestMethod.POST)
	public String uploadJsons(HttpServletRequest request, @RequestParam("file") MultipartFile file, String fangjian,
			String url, String peidiangui, String wenshidu, String kongtiao, String UPS, String fadianji, String all)
			throws IllegalStateException, IOException {
		RackReadService rackReadService = new RackReadServiceImpl();
		dhlist = new ArrayList<String>();
		URL = url;
		if (null != wenshidu) {
			dhlist.add(wenshidu);
		}
		if (null != peidiangui) {
			dhlist.add(peidiangui);
		}
		if (null != kongtiao) {
			dhlist.add(kongtiao);
		}
		if (null != UPS) {
			dhlist.add(UPS);
		}
		if (null != fadianji) {
			dhlist.add(fadianji);
		}
		if (null != all) {
			System.out.println("------------------------------------------------------------------------");
			dhlist.add("温湿度");
			dhlist.add("配电柜");
			dhlist.add("空调");
			dhlist.add("UPS");
			dhlist.add("发电机");
		}
		System.out.println("房间编号为:");
		if (fangjian != null) {
			fjlist = new ArrayList<String>();
			String[] sourceStrArray = fangjian.split(",");
			for (int i = 0; i < sourceStrArray.length; i++) {
				if (!"".equals(sourceStrArray[i])) {
					fjlist.add(sourceStrArray[i]);
					System.out.print(sourceStrArray[i]);
				}
			}
		}
		if (!file.isEmpty()) {
			// 上传文件路径
			String path = request.getServletContext().getRealPath("/upload");
			// 上传文件名
			String filename = file.getOriginalFilename();
			File filepath = new File(path, filename);
			// 判断路径是否存在，如果不存在就创建一个
			if (!filepath.getParentFile().exists()) {
				filepath.getParentFile().mkdirs();
			}
			// 将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			String filePath = path + File.separator + filename;
			System.out.println("文件上传成功");
			System.out.println("文件路径：" + path + File.separator + filename);
			if (fjlist.size() != 0) {
				donghuanMap = rackReadService.readDongHuan(filePath, dhlist, fjlist);
			} else {
				donghuanMap = rackReadService.readDongHuan(filePath, dhlist);
			}
			// System.out.println("动环编号:"+JSONObject.fromObject(donghuanMap));
			return ("/uploadPerfs.action");
		}
		return ("pref_one.html");
	}

	/**
	 * tarsier-推送性能数据
	 * 
	 * @author LiaoMinJun
	 */
	@RequestMapping("/uploadPerfs")
	public String uploadPerfs(HttpServletRequest request) {

		String classPath = this.getClass().getResource("/").getPath();
		System.out.println("读取数据：" + classPath + "perfsetup.json");

		HttpSendPerf hrPerf = new HttpSendPerf();
		JsonManageService service = new JsonManageServiceImpl();
		JSON dhjson = service.donghuanManage(donghuanMap, classPath + "perfsetup.json");
		String jsonstr = FormatUtil.formatJson(dhjson.toString());
		// System.out.println("动环数据:"+dhjson.toString());
		System.out.println("推送服务:" + URL);
		// hrPerf.pushEp(dhjson, URL);
		String resl = hrPerf.pushEp(dhjson, URL);
		if (resl != null) {
			JSONObject jsStr = JSONObject.fromObject(resl);
			if (jsStr.getString("code").equals("200")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "成功");
				System.gc();
				return "pref_succeed.jsp";
			}
			/*if (jsStr.getString("success").equals("false")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "失败");
				System.gc();
				return "pref_succeed.jsp";
			}*/
		}
		request.setAttribute("data", jsonstr);
		System.gc();
		return "pref_fail.jsp";
	}

	/**
	 * 自定义设备编号推送动环数据-用于itvop
	 * 
	 * @param ip
	 * @param peidiangui
	 * @param wenshidu
	 * @param kongtiao
	 * @param UPS
	 * @param fadianji
	 * @return
	 */
	@RequestMapping("/DIYIduploadperf")
	public String DIYIduploadperf(String ip, String peidiangui, String wenshidu, String kongtiao, String UPS,
			String fadianji) {

		String classPath = this.getClass().getResource("/").getPath();
		System.out.println("读取数据：" + classPath + "perfsetup.json");

		JsonManageService service = new JsonManageServiceImpl();
		donghuanMap = new HashMap<String, List<String>>();
		if (null != ip && !"".equals(ip)) {
			IP = ip;
		}
		System.out.println("推送IP:" + IP);
		donghuanMap = service.shebeilistMange(peidiangui, wenshidu, kongtiao, UPS, fadianji);
		System.out.println("动环编号:" + JSONObject.fromObject(donghuanMap));
		JSON dhjson = service.donghuanManage(donghuanMap, classPath + "/perfsetup.json");
		ActiveMQPusher perfacmq = new ActiveMQPusher("admin", "admin", "tcp://" + IP + ":61616", "perfQueue");
		System.out.println("动环数据:" + dhjson.toString());
		perfacmq.push2ActiveMQ(dhjson.toString());
		System.gc();
		return "pref_succeed.html";
	}

	/**
	 * 自定义设备编号推送动环数据-用于tarsier
	 * 
	 * @param URL
	 * @param peidiangui
	 * @param wenshidu
	 * @param kongtiao
	 * @param UPS
	 * @param fadianji
	 * @return
	 */
	@RequestMapping("/DIYIduploadperfs")
	public String DIYIduploadperfs(HttpServletRequest request, String url, String peidiangui, String wenshidu,
			String kongtiao, String UPS, String fadianji) {

		String classPath = this.getClass().getResource("/").getPath();
		System.out.println("读取数据：" + classPath + "perfsetup.json");

		JsonManageService service = new JsonManageServiceImpl();
		HttpSendPerf hrPerf = new HttpSendPerf();
		donghuanMap = new HashMap<String, List<String>>();
		URL = url;
		System.out.println("推送服务url:" + URL);
		donghuanMap = service.shebeilistMange(peidiangui, wenshidu, kongtiao, UPS, fadianji);
		System.out.println("动环编号:" + JSONObject.fromObject(donghuanMap));
		JSON dhjson = service.donghuanManage(donghuanMap, classPath + "/perfsetup.json");
		String jsonstr = FormatUtil.formatJson(dhjson.toString());
		// System.out.println("动环数据:"+dhjson.toString());
		String resl = hrPerf.pushEp(dhjson, URL);
		if (resl != null) {
			JSONObject jsStr = JSONObject.fromObject(resl);
			if (jsStr.getString("code").equals("200")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "成功");
				System.gc();
				return "pref_succeed.jsp";
			}
			/*if (jsStr.getString("success").equals("false")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "失败");
				System.gc();
				return "pref_succeed.jsp";
			}*/
		}
		request.setAttribute("data", jsonstr);
		System.gc();
		return "pref_fail.jsp";
	}

	/**
	 * 架式设备编号推送性能数据-用于tarsier
	 * 
	 * @return
	 */
	@RequestMapping("/fuwuqiIduploadperf")
	public String fuwuqiIduploadperf(HttpServletRequest request, String cicode, String curl, String all, String CPU,
			String Memory, String DiskIO, String NetworkIO, String Connect) {
		JsonManageService service = new JsonManageServiceImpl();
		HttpSendPerf hrPerf = new HttpSendPerf();
		List<String> cilist = new ArrayList<String>();
		List<String> kpilist = new ArrayList<String>();
		if (null != all) {
			System.out.println("------------------------------------------------------------------------");
			kpilist.add("CPU使用率");
			kpilist.add("内存");
			kpilist.add("磁盘I/O");
			kpilist.add("网络I/O");
			kpilist.add("连接数");

		}
		if (null != CPU) {
			kpilist.add(CPU);
		}
		if (null != Memory) {
			kpilist.add(Memory);
		}
		if (null != DiskIO) {
			kpilist.add(DiskIO);
		}
		if (null != NetworkIO) {
			kpilist.add(NetworkIO);
		}
		if (null != Connect) {
			kpilist.add(Connect);
		}
		System.out.print("推送设备id:");
		String[] sourceStrArray = cicode.split(",");
		for (int i = 0; i < sourceStrArray.length; i++) {
			if (!"".equals(sourceStrArray[i])) {
				cilist.add(sourceStrArray[i]);
				System.out.print(sourceStrArray[i] + "、");
			}
		}
		System.out.println();
		JSON fwqjson = service.fuwuqiperfManage(cilist, kpilist);
		String jsonstr = FormatUtil.formatJson(fwqjson.toString());
		// System.out.println("性能数据:"+fwqjson.toString());
		String resl = hrPerf.pushEp(fwqjson, curl);
		if (resl != null) {
			JSONObject jsStr = JSONObject.fromObject(resl);
			if (jsStr.getString("code").equals("200")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "成功");
				System.gc();
				return "pref_succeed.jsp";
			}
			/*if (jsStr.getString("success").equals("false")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "失败");
				System.gc();
				return "pref_succeed.jsp";
			}*/
		}
		request.setAttribute("data", jsonstr);
		System.gc();
		return "pref_fail.jsp";
	}

	/**
	 * 架式设备编号批量推送性能数据-用于tarsier
	 * 
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping("/fuwuqiIdsuploadperf")
	public String fuwuqiIdsuploadperf(HttpServletRequest request, @RequestParam("file") MultipartFile file, String curl,
			String all, String CPU, String Memory, String DiskIO, String NetworkIO, String Connect)
			throws IllegalStateException, IOException {
		JsonManageService service = new JsonManageServiceImpl();
		ReadExcel readExcel = new ReadExcel();
		HttpSendPerf hrPerf = new HttpSendPerf();
		List<String> cilist = new ArrayList<String>();
		List<String> kpilist = new ArrayList<String>();
		String jsonstr = null;
		if (!file.isEmpty()) {
			if (null != all) {
				System.out.println("------------------------------------------------------------------------");
				kpilist.add("CPU使用率");
				kpilist.add("内存");
				kpilist.add("磁盘I/O");
				kpilist.add("网络I/O");
				kpilist.add("连接数");

			}
			if (null != CPU) {
				kpilist.add(CPU);
			}
			if (null != Memory) {
				kpilist.add(Memory);
			}
			if (null != DiskIO) {
				kpilist.add(DiskIO);
			}
			if (null != NetworkIO) {
				kpilist.add(NetworkIO);
			}
			if (null != Connect) {
				kpilist.add(Connect);
			}

			// 上传文件路径
			String path = request.getServletContext().getRealPath("/upload");
			// 上传文件名
			String filename = file.getOriginalFilename();
			File filepath = new File(path, filename);
			// 判断路径是否存在，如果不存在就创建一个
			if (!filepath.getParentFile().exists()) {
				filepath.getParentFile().mkdirs();
			}
			// 将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			String filePath = path + File.separator + filename;
			System.out.println("文件上传成功");
			System.out.println("文件路径：" + path + File.separator + filename);
			// 读取批量cicode
			cilist = readExcel.ReadExcelColumn(filePath);
			// 处理ci返回指定数据
			JSON fwqjson = service.fuwuqiperfManage(cilist, kpilist);
			jsonstr = FormatUtil.formatJson(fwqjson.toString());
			// System.out.println("性能数据:"+fwqjson.toString());
			String resl = hrPerf.pushEp(fwqjson, curl);
			if (resl != null) {
				JSONObject jsStr = JSONObject.fromObject(resl);
				if (jsStr.getString("code").equals("200")) {
					request.setAttribute("resl", resl);
					request.setAttribute("data", jsonstr);
					request.setAttribute("zhuantai", "成功");
					System.gc();
					return "pref_succeed.jsp";
				}
				/*if (jsStr.getString("success").equals("false")) {
					request.setAttribute("resl", resl);
					request.setAttribute("data", jsonstr);
					request.setAttribute("zhuantai", "失败");
					System.gc();
					return "pref_succeed.jsp";
				}*/
			}
		}
		request.setAttribute("data", jsonstr);
		System.gc();
		return "pref_fail.jsp";
	}

	/**
	 * ci推送自定义性能数据-用于tarsier
	 * 
	 * @return
	 */
	@RequestMapping("/ciIduploadperf")
	public String ciIduploadperf(HttpServletRequest request, String CI, String KPI, String UNIT, String VALUE,
			String CIURL) {
		HttpSendPerf hrPerf = new HttpSendPerf();
		JSONArray jsonArray = new JSONArray();
		JSON json = new JSONArray();
		// 修改时间戳
		/*
		 * Date date=new Date(); DateFormat format=new SimpleDateFormat(
		 * "yyyy-MM-dd HH:mm:ss"); String time=format.format(date);
		 */
		String time = String.valueOf(System.currentTimeMillis());
		JsonManageServiceImpl service = new JsonManageServiceImpl();
		service.perf(CI, KPI, VALUE, UNIT, "_", time);
		JSONObject jsonObj = service.perf(CI, KPI, VALUE, UNIT, "_", time);
		jsonArray.add(jsonObj);
		json = jsonArray;
		String jsonstr = FormatUtil.formatJson(json.toString());
		System.out.println("推送设备id:" + CI);
		// System.out.println("性能数据:"+json.toString());
		String resl = hrPerf.pushEp(json, CIURL);
		if (resl != null) {
			JSONObject jsStr = JSONObject.fromObject(resl);
			if (jsStr.getString("code").equals("200")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "成功");
				System.gc();
				return "pref_succeed.jsp";
			}
			/*if (jsStr.getString("success").equals("false")) {
				request.setAttribute("resl", resl);
				request.setAttribute("data", jsonstr);
				request.setAttribute("zhuantai", "失败");
				System.gc();
				return "pref_succeed.jsp";
			}*/
		}
		request.setAttribute("data", jsonstr);
		System.gc();
		return "pref_fail.jsp";
	}

	@RequestMapping("/perfsetupout")
	public String perfsetupout(HttpServletRequest request) {
		DongHuan dHuan = new DongHuan();
		jsonManageService = new JsonManageServiceImpl();

		String classPath = this.getClass().getResource("/").getPath();
		System.out.println("读取数据：" + classPath + "perfsetup.json");

		dHuan = jsonManageService.readPerfSetUpJson(classPath + "perfsetup.json");
		request.setAttribute("dHuan", dHuan);
		return "prefsetup.jsp";
	}

	@RequestMapping("/perfsetupin")
	public String perfsetupin(HttpServletRequest request, DongHuan dongHuan) {
		jsonManageService = new JsonManageServiceImpl();

		String classPath = this.getClass().getResource("/").getPath();
		System.out.println("写入数据：" + classPath + "perfsetup.json");

		boolean rel = jsonManageService.writePerfSetUpJson(classPath + "perfsetup.json", dongHuan);
		if (rel) {
			request.setAttribute("zhuantai", "✔");
			return "/perfsetupout.action";
		}
		request.setAttribute("zhuantai", "✘");
		return "perfsetup.jsp";
	}

}
